#include <stdio.h>
#include <stdlib.h>
#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"

static int fps;

int frame_lock_check(int framerate)
{
	static float last = 0.0f;

	float current = SDL_GetTicks() * 0.001f;

	if ((current - last) > (1.0f / framerate))
	{
		/* Framerate lock has expired, we can continue with drawing. */
		return 1;
	}
	/* Else, the framerate is still locked. */
	return 0;
}

int init_GL(const SDL_VideoInfo * vid)
{
	/* Set the default colour of the screen to black. */
	glClearColor(0,0,0,0);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, vid->current_w, vid->current_h, 0, -1, 1);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	return glGetError() == GL_NO_ERROR;
}

void determine_fps()
{
	static int start_ticks = 0;
	static int frames_since_reset;

	/* Handle the special case where start_ticks is zero (first call of this function). */

	if (!start_ticks)
	{
		start_ticks = SDL_GetTicks();
	}
	
	int current_ticks = SDL_GetTicks();

	if ((current_ticks - start_ticks) <= 1000)
	{
		/* Add us as a frame. */
		frames_since_reset++;
	}
	else
	{
		fps = frames_since_reset;
		printf("FPS: %d", fps);
		/* We're the first frame in this second. */
		frames_since_reset = 1;
		start_ticks = SDL_GetTicks();
	}
}

void update()
{
	/* determine_fps(); */
}

void draw()
{
	
}

int main(int argc, char ** argv)
{
	/* Py_Initialize(); */
	/* /\* The reason we register Py_Finalize as an atexit hook is that there may be times when the program quits with a exit() call. *\/ */
	/* atexit(Py_Finalize); */

	/* /\* Initialize the Endian graphics library. *\/ */
	/* initendgfx(); */
	
	/* Initialise SDL */

	int quit = 0;
	SDL_Event * event;
	const SDL_VideoInfo * vid;
	/* This should be set to a different value if an error occurs. */
	int ret = 0;

	if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		fprintf(stderr, "Error: Could not initialise SDL.\n");
		return 1;
	}
	fprintf(stderr, "SDL initialisation complete.\n");
	if (!(vid = SDL_GetVideoInfo()))
	{
		fprintf(stderr, "Error: Could not get information about the best video mode.\n");
	}
	fprintf(stderr, "Window information successfully gathered.\n");
	fprintf(stderr, "Current resoloution: %d w, %d h\n", vid->current_w, vid->current_h);
	if (SDL_SetVideoMode(vid->current_w, vid->current_h, 0, SDL_OPENGL) == NULL)
	{
		fprintf(stderr, "Error: Could not create window.\n");
		return 1;
	}
	fprintf(stderr, "Window successfully created.\n");
	if (!init_GL(vid))
	{
		fprintf(stderr, "Error: Could not initialise OpenGL.\n");
		return 1;
	}
	fprintf(stderr, "OpenGL successfully initialised.\n");
	
	SDL_WM_SetCaption( "OpenGL Test", NULL );

	while (!quit)
	{
		while (SDL_PollEvent(event))
		{
			
			if (event->type == SDL_QUIT)
			{
				quit = 1;
			}
		}

		/* TODO: Define draw() and update() */
		/* Check to see if we should be doing an update. */
		if (frame_lock_check(60))
		{
			update();
		}

		glClear(GL_COLOR_BUFFER_BIT);

		draw();

		SDL_GL_SwapBuffers();
	}
}
